<template>
  <div class="as-radio"
       :class="[{'is-disabled':disabled,   
                 'is-button': button,
                 'is-border': border},
                 radioSize?'as-radio--'+radioSize:'']"
       @click="disabled?'':model=label">
    <span class="as-radio__inner"
          :class="{'is-checked': model === label,
                   'is-disabled': disabled,
                   'is-button': button,
                   'is-border': border}">
      <input type="radio"
             :disabled="disabled"
             ref="radio"
             :value="label"
             v-model="model">
    </span>
    <label class="as-radio__label"
           :class="{'is-disabled':disabled,   
                    'is-button': button,
                    'is-border': border}">
      <slot></slot>
      <span v-if="!($slots&&$slots.default)">{{value}}</span>
    </label>
  </div>
</template>

<script type='text/ecmascript-6'>
import emitter from "../../../mixin";
export default {
  name: "AsRadio",
  mixins: [emitter],
  props: {
    label: {},
    value: {},
    disabled: Boolean,
    size: String,
    button: Boolean,
    border: Boolean
  },
  computed: {
    radioSize() {
      return this.isRadioGroup ? this._radioGroup.size || this.size : this.size;
    },
    isRadioGroup() {
      let parent = this.$parent;
      while (parent) {
        if (parent.$options.componentName !== "AsRadioGroup") {
          parent = parent.$parent;
        } else {
          this._radioGroup = parent;
          return true;
        }
      }

      return false;
    },
    model: {
      // 赋值
      set(val) {
        if (this.isRadioGroup) {
          this.dispatch("AsRadioGroup", "handlerChange", [val]);
        } else {
          this.$emit("change", val);
          this.$emit("input", val);
        }
        this.$refs.radio.checked = val === this.label;
      },
      // 获取
      get() {
        return this.isRadioGroup ? this._radioGroup.value : this.value;
      }
    }
  },
  data() {
    return {
      _radioGroup: null
    };
  }
};
</script>
